<template>
  <!-- 城市选择 -->
  <div class="city-view">
    <!-- 头部 -->
    <city-header></city-header>
    <!-- 搜索框 -->
    <city-search></city-search>
    <!-- 列表 -->
    <city-list :list="cities" :hotList="hotCities" :letter="letter"></city-list>
    <!-- 字母表 -->
    <city-alphabet :list="cities" @change="handleLetter"></city-alphabet>
  </div>
</template>

<script>
import axios from 'axios'
import CityHeader from './cpns/CityHeader.vue'
import CitySearch from './cpns/CitySearch.vue'
import CityList from './cpns/CityList.vue'
import CityAlphabet from './cpns/CityAlphabet.vue'
export default {
  name: 'CityView',
  components: {
    CityHeader,
    CitySearch,
    CityList,
    CityAlphabet,
  },
  data() {
    return {
      cities: [],
      hotCities: [],
      letter: '',
    }
  },
  mounted() {
    this.getData()
    this.forbidPull(true)
  },
  beforeRouteLeave(to, from, next) {
    this.forbidPull(false)
    next()
  },
  methods: {
    getData() {
      axios.get('/api/city.json').then((res) => {
        res = res.data
        if (res.code === 200 && res.data) {
          this.cities = res.data.cities
          this.hotCities = res.data.hotCities
        }
      })
    },
    handleLetter(val) {
      this.letter = val
    },
    // 阻止默认的处理方式(阻止下拉滑动的效果)
    handlePrevent(e) {
      e.preventDefault()
    },
    // 阻止下拉滑动的效果
    forbidPull(type) {
      if (type == true) {
        document.body.addEventListener('touchmove', this.handlePrevent, { passive: false })
      } else if (type == false) {
        document.body.removeEventListener('touchmove', this.handlePrevent, { passive: false })
      }
    },
  },
}
</script>

<style lang="scss" scoped></style>
